import store from '@/store/index'
import config from './config.js'

export default function({
	url,
	data = {},
	method,
	needToken = true, //是否需要token，默认开启
	isLoading = false, //是否开启loading
}) {
	if (isLoading) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: config.baseUrl + url,
			data,
			method,
			timeout: 30 * 1000,
			header: {
				'Authorization': needToken ? `Bearer ${uni.getStorageSync('token')}` : '' //填充token的方式，可选择性修改
			},
			success(res) {
				let respData = res.data;

				if (respData.code === 500 || respData.status === 500) {
					uni.showToast({
						title: respData.msg,
						icon: 'none'
					})

					reject(respData);
					return;
				}

				if (respData.code === 401) {
					reject(respData);
					return;
				}

				uni.hideLoading();
				resolve(respData);
			},
			fail(error) {
				reject(error);
			},
			complete() {
				uni.hideLoading();
			}
		})
	})
}
